import axios from 'axios'
import type { AxiosError, InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import { REQUEST_OUTTIME } from '@/utils/constant'
import { getToken } from '@/utils/auth'
import { notification } from 'ant-design-vue'

const [api] = notification.useNotification()

enum ResponeCode {
  Success = 200,
  Error = 500,
  NotFound = 404,
  Unauthorized = 401,
  Forbidden = 403,
  BadRequest = 400
}

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: REQUEST_OUTTIME
})

// 请求拦截器
function ResquestInterceptor(config: InternalAxiosRequestConfig): InternalAxiosRequestConfig {
  const token = getToken()
  if (token) {
    config.headers!.Authorization = `Bearer ${token}`
  }
  return config
}

// 请求拦截器错误处理
function ResquestInterceptorError(error: AxiosError): Promise<AxiosError> {
  return Promise.reject(error)
}

function ResponeInterceptor<T>(respone: AxiosResponse<T>):Promise<T>  {
  const { code, message } = respone.data as ResponseData<T>
  if (code !== ResponeCode.Success) {
    if (code === ResponeCode.Unauthorized || code === ResponeCode.Forbidden) {
      api.error({
        message: '请求错误',
        description: message
      })
      return Promise.reject(new Error(message))
    }
    return Promise.reject(new Error(message))
  }
  return Promise.resolve(respone.data)
}

function ResponeInterceptorError(error: AxiosError): Promise<AxiosError> {
  return Promise.reject(error)
}

// 添加请求拦截器

service.interceptors.request.use(ResquestInterceptor, ResquestInterceptorError)

service.interceptors.response.use(ResponeInterceptor, ResponeInterceptorError)
export default service
